﻿//Copyright (c) 2010 Michael Ey

//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace GameTrakFlashServer
{
    public partial class GameTrakServer : Form
    {
        delegate void SetLabelText(Label box, string text);
        delegate void StartTimerDelegate();

        private bool m_isRunning = false;
        private TcpListener m_broadcastSocket;
        private TcpClient m_flashGameTrak;
        private BinaryWriter m_networkStream;
        private GameTrakXNA31.GameTrakService m_gameTrak;
        
        public GameTrakServer()
        {
            InitializeComponent();

            m_gameTrak = new GameTrakXNA31.GameTrakService(this.Handle);
        }

        private void m_startButton_Click(object sender, EventArgs e)
        {
            if (!m_isRunning)
            {
                try
                {
                    m_broadcastSocket = new TcpListener(IPAddress.Loopback, Convert.ToInt32(m_portBox.Text));
                    m_broadcastSocket.Start();
                    m_broadcastSocket.BeginAcceptTcpClient(new AsyncCallback(ConnectionRecieved), new object());

                    m_isRunning = true;

                    m_status.Text = "Listening For Connection...";
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }
        }

        private void SetTextOnLabel(Label box, string text)
        {
            box.Text = text;
        }

        private void StartTimer()
        {
            try
            {
                m_pollTimer.Interval = Convert.ToInt32(m_intervalBox.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("Poll Interval Invalid: using 8ms!");
                m_pollTimer.Interval = 8;
            }

            m_pollTimer.Tick += new EventHandler(m_pollTimer_Tick);
            m_pollTimer.Start();
        }

        private void StopTimer()
        {
            m_pollTimer.Stop();
            m_pollTimer.Tick -= m_pollTimer_Tick;
            m_isRunning = false;
            m_broadcastSocket.Stop();
        }

        private void ConnectionRecieved(IAsyncResult result)
        {
            m_flashGameTrak = m_broadcastSocket.EndAcceptTcpClient(result);
            m_networkStream = new BinaryWriter(m_flashGameTrak.GetStream());

            if (m_status.InvokeRequired)
            {
                SetLabelText d = new SetLabelText(SetTextOnLabel);
                this.Invoke(d, new object[] { m_status, "Connected!" });

                StartTimerDelegate std = new StartTimerDelegate(StartTimer);
                this.Invoke(std);
            }
            else
            {
                m_status.Text = "Connected!";
                StartTimer();
            }
        }

        void m_pollTimer_Tick(object sender, EventArgs e)
        {
            m_gameTrak.Poll();
            GameTrakXNA31.GameTrakState state;
            m_gameTrak.getState(out state);

            try
            {
                
                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.LeftCord.X * short.MaxValue)));
                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.LeftCord.Y * short.MaxValue)));
                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.LeftCord.Z * short.MaxValue)));

                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.RightCord.X * short.MaxValue)));
                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.RightCord.Y * short.MaxValue)));
                m_networkStream.Write(IPAddress.HostToNetworkOrder((short)(state.RightCord.Z * short.MaxValue)));

                if (state.BigButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                {
                    m_networkStream.Write(IPAddress.HostToNetworkOrder((short)1));
                }
                else
                {
                    m_networkStream.Write(IPAddress.HostToNetworkOrder((short)0));
                }
            }
            catch (IOException)
            {
                if (m_status.InvokeRequired)
                {
                    SetLabelText d = new SetLabelText(SetTextOnLabel);
                    this.Invoke(d, new object[] { m_status, "Connection Lost!" });

                    StartTimerDelegate std = new StartTimerDelegate(StopTimer);
                    this.Invoke(std);
                }
                else
                {
                    m_status.Text = "Connection Lost!";
                    StopTimer();
                }
            }
        }

        private void GameTrakServer_FormClosed(object sender, FormClosedEventArgs e)
        {
            m_pollTimer.Stop();
            m_broadcastSocket.Stop();
        }
    }
}
